package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 107 二叉树的层序遍历 II
 * @date 2025/1/11 12:50
 */
public class E107 {

    /**
     * <h3>方法一：用双端队列的特性</h3>
     *
     * @param root 根节点
     * @return 从底向上层序遍历结果
     */
    @SuppressWarnings("all")
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<List<Integer>> result = new LinkedList<>();
        if (root == null) return result;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null)
                    queue.offer(poll.left);
                if (poll.right != null)
                    queue.offer(poll.right);
                level.add(poll.val);
            }
            result.offerFirst(level);
        }
        return result;
    }
}
